import axios from 'axios';
import Wcore from '@/libs/common.js';
import Wupload from './Wupload.js';

/*

*/
let http = {
	token_time:0
};

if(process.env.NODE_ENV=='development') {

	
	 http = {
	 	upload_url:'http://www.ling.org/upload/index.php',
	 	apiUrl:"http://www.ling.org/admin.php/",
	 	baseUrl:'http://www.ling.org/'
	 };
}
else{
	http = {
		upload_url:'http://112.74.132.131:8668/upload/index.php',
		apiUrl:"http://112.74.132.131:8668/admin.php/",
		baseUrl:'http://112.74.132.131:8668/'
	};
}

var timer = null;

http.load = function(uri,postdata,callback,fail_call){
	var self = this;
	let qs = require('qs');
	let url = this.apiUrl;
	
	
	//'Content-Type': 'application/x-www-form-urlencoded'
	//'Content-Type': 'application/json'
	let headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
		
    };
	var fail_call = fail_call || true;
	
	
	this.token = Wcore.getData(Wcore.prefix('token'));
	postdata['token'] = this.token;
	postdata['token_time'] = self.token_time;
	//qs.stringify(postdata)
	
	axios.post(url+uri, qs.stringify(postdata),{
        headers: headers
	})
	.then(function (response){
		if(response.data.time){
			self.token_time = response.data.time;
		}
		

		if(response.data.result_code==0){
			typeof(callback)=='function' && callback(response.data.data);
		}
		else if(response.data.result_code==401){
			Wcore.setData(Wcore.prefix('token'),'');
			
			clearTimeout(timer);
			timer = setTimeout(logout_handle,1000);
		}
		else{
			if(fail_call===true){
				alert(response.data.message);
			}
			else if(typeof(fail_call)=='function'){
				fail_call(response.data);
			}
		}
		
	})
	.catch(function (response) {
		typeof(fail_call)=='function' && fail_call(response);
	});
}

function logout_handle(){
	alert('已退出登录');
	window.location.reload();
}

http.uploadBigFile = function(file,url,postdata,call){
	
	let base_url = this.apiUrl;
	var curl = base_url +'/'+ url;
	
	var token = Wcore.getData(Wcore.prefix('token'));
	postdata['token'] = token;
	
	var upload = new Wupload(curl,file,postdata);
	/*
	var toast = Toast.loading({
		duration: 0,       // 持续展示 toast
		forbidClick: true, // 禁用背景点击
		loadingType: 'spinner',
		message: '正在上传中，进度0%'
	});
	*/
	
	upload.init(function(result){
		//Toast.clear();
		typeof(call)=='function' && call(result);
	});

	
	upload.onProgress(function(status,progress,res){
		//toast.message = '正在上传中，进度'+progress+'%';
	});
	
	return upload;
}



export default http;
